package cn.sdormitory.controller.smartdor;


import cn.sdormitory.basedata.entity.BClass;
import cn.sdormitory.basedata.entity.BDormitory;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.basedata.service.BStudentService;
import cn.sdormitory.common.annotation.IgnoreAuth;
import cn.sdormitory.common.annotation.SysLog;
import cn.sdormitory.common.api.CommonResult;
import cn.sdormitory.common.enums.BusinessType;
import cn.sdormitory.smartdor.entity.SdHygiene;
import cn.sdormitory.smartdor.service.SdManualAttenceService;
import cn.sdormitory.smartdor.service.SdManualHygieneService;
import cn.sdormitory.smartdor.vo.SdManualAttenceVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.security.Principal;
import java.text.ParseException;
import java.util.List;
import java.util.Objects;

@RestController
@Api(tags = "Smartdor-manualHygiene=> 卫生考核")
@RequestMapping("/smartdor/manualHygiene")
public class SdManualHygieneController {
    @Resource
    private SdManualAttenceService sdManualAttenceService;

    @Resource
    private SdManualHygieneService sdManualHygieneService;

    @Resource
    private BStudentService bStudentService;

    @ApiOperation("list => 查询卫生考核列表")
    @PreAuthorize("@ss.hasPermi('smartdor:manualHygiene:list')")
    @GetMapping(value = "/manualHygieneList")
    public CommonResult<List<SdManualAttenceVo>> list() throws ParseException {
        List<SdManualAttenceVo> manualAttenceVoList = sdManualAttenceService.getManualAttenceList();
        return CommonResult.success(manualAttenceVoList);

    }

    /**
     * 获取图片
     *
     * @param id
     * @param width
     * @param height
     * @param response
     * @throws IOException
     */
    @IgnoreAuth
    @ApiOperation("/getPhoto.do => 获取卫生考核照片")
    @GetMapping("/getPhoto.do")
    public void getPhotoById(Long id, int width, int height, final HttpServletResponse response) throws IOException {
        //BStudent bStudentInfo = bStudentService.getBStudentById(id);
        System.out.println("........... getPhotoById "+id);
        SdHygiene sdHygiene = sdManualHygieneService.getSdHygieneById(id);
        System.out.println("获取了数据： "+sdHygiene.getCheckDate()+"\t\t "+sdHygiene.getPhoto() +"\t "+sdHygiene.getPhoto().length);
        byte[] data = sdHygiene.getPhoto();
        if (width != 0 && height != 0) {
            data = scaleImage(data, width, height);
        }
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputSream = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            outputSream.write(buf, 0, len);
        }
        outputSream.close();
    }
    /**
     * 显示图片
     *
     * @param data   byet流
     * @param width  图片的宽度
     * @param height 图片的高度
     * @return 2020.11.19
     * @throws IOException
     */
    public static byte[] scaleImage(byte[] data, int width, int height) throws IOException {
        BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));
        int imageOldWidth = buffered_oldImage.getWidth();
        int imageOldHeight = buffered_oldImage.getHeight();
        double scale_x = (double) width / imageOldWidth;
        double scale_y = (double) height / imageOldHeight;
        double scale_xy = Math.min(scale_x, scale_y);
        int imageNewWidth = (int) (imageOldWidth * scale_xy);
        int imageNewHeight = (int) (imageOldHeight * scale_xy);
        BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);
        buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);
        buffered_newImage.getGraphics().dispose();
        ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();
        ImageIO.write(buffered_newImage, "jpeg", outPutStream);
        return outPutStream.toByteArray();
    }
    /**
     * 文件上传（表单和文件同步上传）
     *
     * @returncreate
     */
    @PreAuthorize("@ss.hasPermi('basedata:bshygiene:add')")
    @ApiOperation("createHygiene => 新建卫生考核")
    @PostMapping(value = "/createHygiene")
    public CommonResult saveHygiene(@RequestParam(value = "upload") MultipartFile upload, SdHygiene sdHygiene,Principal principal) {
        System.out.println("************************************* ------------ upload :"+upload.getOriginalFilename()  +" \t \t sdHygiene "+sdHygiene);


        byte[] pictureData = null;
        // 使用输入流获取上传的图片
        InputStream inputStream = null;
        try {
            inputStream = upload.getInputStream();
            // 定义字节数组用于存放图片信息
            pictureData = new byte[(int) upload.getSize()];
            // 读取图片到字节数组中
            inputStream.read(pictureData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sdHygiene.setPhoto(pictureData);
        sdHygiene.setCreateBy(principal.getName());

        int count = sdManualHygieneService.create(sdHygiene);
        System.out.println("............. count : "+count);
        if (count >0 ){
            CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("create => 新建卫生考核")
    @PreAuthorize("@ss.hasPermi('basedata:bshygiene:add')")
    //@SysLog(title = "卫生考核管理", businessType = BusinessType.INSERT)
    @PostMapping(value = "/create")
    public CommonResult<Integer> create(@RequestBody SdHygiene sdHygiene,Principal principal) throws IOException {

        System.out.println("------- 增加无附件考核信息： "+sdHygiene);

        sdHygiene.setCreateBy(principal.getName());
        int count = sdManualHygieneService.create(sdHygiene);
        System.out.println("............. count : "+count);
        if (count >0 ){
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("updateAndUpload/ => 修改卫生考核信息(包含文件上传)")
    @PreAuthorize("@ss.hasPermi('basedata:bshygiene:edit')")
    @PostMapping (value = "/updateAndUpload")
    public CommonResult<Integer> updateAndUpload(@RequestParam(value = "upload") MultipartFile upload, SdHygiene sdHygiene) {
        System.out.println("...............  修改卫生考核信息，带附件方式"+upload+"\t\t sdHygiene :"+sdHygiene);

        byte[] pictureData = null;
        // 使用输入流获取上传的图片
        InputStream inputStream = null;
        try {
            inputStream = upload.getInputStream();
            // 定义字节数组用于存放图片信息
            pictureData = new byte[(int) upload.getSize()];
            // 读取图片到字节数组中
            inputStream.read(pictureData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sdHygiene.setPhoto(pictureData);

        int count = sdManualHygieneService.update(sdHygiene.getId(),sdHygiene);
        System.out.println("............. count : "+count);
        if (count >0 ){
            CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("update/{id} =>修改卫生考核信息")
    @PreAuthorize("@ss.hasPermi('basedata:bshygiene:edit')")
    @SysLog(title = "卫生考核管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/update/{id}")
    public CommonResult<Integer> update(@PathVariable Long id, @RequestBody SdHygiene sdHygiene) {
        //根据班级ID查询班级名称
        int count = sdManualHygieneService.update(sdHygiene.getId(),sdHygiene);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }



    @IgnoreAuth
    @ApiOperation("getHygieneByDormitoryIdAdndCheckDate=>根据宿舍ID和 考核时间查询卫生考核信息")
    @GetMapping("/getHygieneByDormitoryIdAdndCheckDate")
    /**
     * 根据宿舍ID和 考核时间查询卫生考核信息
     * @param dormitoryId
     * @param checkDate
     * @return
     */
    public CommonResult<SdHygiene> getHygieneByDormitoryIdAdndCheckDate(Long dormitoryId,String checkDate){
        System.out.println("............................ 开始执行查询： dormitoryId :"+dormitoryId+"\t \t checkDate :"+checkDate);
        return CommonResult.success(sdManualHygieneService.getHygieneByDormitoryIdAdndCheckDate(dormitoryId,checkDate));
    }
}
